package com.github.live.manager;

import android.content.Context;
import android.text.TextUtils;

import com.github.live.R;
import com.github.live.util.LogFactory;
import com.github.livebase.bean.IjkCodec;
import com.github.live.player.render.SurfaceRenderViewFactory;
import com.github.live.util.store.HawkConfig;
import com.github.live.util.store.HawkStorage;
import com.github.livebase.bean.Channel;
import com.github.livebase.player.IMediaPlayer;
import com.github.livebase.util.base.CollectionsUtil;
import com.github.livebase.util.base.ObjectsUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import xyz.doikki.videoplayer.player.LiveVideoView;
import xyz.doikki.videoplayer.render.TextureRenderViewFactory;

/**
 * @ClassName SettingManager
 * @description: 设置管理
 * @author: biao532
 * @create: 2023-12-19 13:47
 * @Version 1.0
 **/
public class SettingManager {
    private LiveVideoView videoView;
    private List<IjkCodec> ijkCodecs;
    private int previousRenderPos = -1;
    private Context mContext;
    private List<String> playerNames;

    protected SettingManager(Context mContext, List<IjkCodec>ijkCodecs) {
        this.mContext = mContext;
        if (CollectionsUtil.isEmpty(ijkCodecs)) {
            IjkCodec codec = new IjkCodec();
            codec.setName("默认");
            codec.setOptions(new ArrayList<>(0));
            ijkCodecs = Arrays.asList(codec);
        }
        this.ijkCodecs = ijkCodecs;
    }
    public void attach(LiveVideoView view) {
        this.videoView = view;
    }
    public String[] groupNames() {
        return mContext.getResources().getStringArray(R.array.setting_group_names);
    }
    public String[] renderNames() {
        return mContext.getResources().getStringArray(R.array.render_name);
    }
    public void resetRenderFactory(int position) {
        if (videoView == null || previousRenderPos == position) {
            return;
        }
        if (position == 0) {
            videoView.setRenderViewFactory(new TextureRenderViewFactory(), true);
        }
        else {
            videoView.setRenderViewFactory(new SurfaceRenderViewFactory(), true);
        }
        this.previousRenderPos = position;
        // 无需释放videoView，只需重设
        // videoView.replay(true);
    }

    public int getTimeoutIndex() {
        return HawkStorage.getStore().get(HawkConfig.LIVE_CONNECT_TIMEOUT, 1);
    }
    public void setTimeoutIndex(int position) {
        HawkStorage.getStore().put(HawkConfig.LIVE_CONNECT_TIMEOUT, position);
    }
    public void setRenderNameIndex(Channel.Source source, int index) {
        HawkStorage.getStore().put(getKey(source, "render"), index);
    }
    public int getRenderNameIndex(Channel.Source source) {
        //return 0;
        int index = HawkStorage.getStore().get(getKey(source, "render"), LiveInitializer.getInitializer()
                .getConfig()
                .getIRendView());
        if (index < 0 || index >= renderNames().length) {
            return 0;
        }
        return index;
    }

    public int getScaleNameIndex(Channel.Source source) {
        int index = HawkStorage.getStore().get(getKey(source, "scale"), 0);
        if (index < 0 || index >= scaleNames().length) {
            return 0;
        }
        return index;
    }

    public void setScaleNameIndex(Channel.Source source, int index) {
        HawkStorage.getStore().put(getKey(source, "scale"), index);
    }

    public int getPlayerNameIndex(Channel.Source source) {
        int index = HawkStorage.getStore().get(getKey(source, "player"), 0);
        if (index < 0 || index >= playerNames().size()) {
            return 0;
        }
        return index;
    }

    public void setPlayerNameIndex(Channel.Source source, int index) {
        HawkStorage.getStore().put(getKey(source, "player"), index);
    }

    private String getKey(Channel.Source source, String key) {
        if (source == null) return String.format("settings-%s-%s", key, "nothing");
        return String.format("settings-%s-%s", key, source.getLive());
    }

    public String[] scaleNames() {
        return mContext.getResources().getStringArray(R.array.scale_name);
    }
    public void resetScale(int position) {
        if (videoView == null) {return;}
        videoView.setScreenScaleType(position);
    }
    public<T> void setSettingAttr(String key, T value) {
        HawkStorage.getStore().put("setting-" + key, value );
    }

    public<T> T getSettingAttr(String key, T value) {
        return HawkStorage.getStore().get("setting-" + key, value);
    }
    public String[] timeoutNames() {
        return mContext.getResources().getStringArray(R.array.timeout_name);
    }
    public String[] preferenceName() {
        return mContext.getResources().getStringArray(R.array.preference_name);
    }

    public List<String> playerNames() {
        if (!CollectionsUtil.isEmpty(playerNames)) {
            return playerNames;
        }
        playerNames = CollectionsUtil.convert(ijkCodecs, i -> i.getName());
        if (CollectionsUtil.isEmpty(playerNames)) {
            playerNames.add("ijkM");
        }
        // playerNames.addAll(0, Arrays.asList("系统", "exo"));
        return playerNames;
    }
    public void resetPlayer(int position, String url) {
        if (videoView == null) {
            return;
        }
        /*else if (checkPre && position == prePlayerPos) {
            resetOptions(position);
            return;
        }*/
        /*if (position == 0) {
            videoView.release();
            videoView.setPlayerFactory(new AndroidMediaIMediaPlayerFactory());
        }
        else if (position == 1) {
            videoView.release();
            videoView.setPlayerFactory(new ExoMediaIMediaPlayerFactory());
        }
        else {
            if (prePlayerPos < 2) {
                videoView.release();
                videoView.setPlayerFactory(new MultiPlayerFactory(LiveInitializer.getInitializer()
                        .getConfig()
                        .getIjkM_maxCount(), new IjkIMediaPlayerFactory()));
            }
        }*/
        IjkCodec ijkCodec = ijkCodecs.get(position % ijkCodecs.size());
        ChannelsManager cm = LiveInitializer.getInitializer()
                .getChannelsManager();
        // 此处只设置option，基于封装的VideoView只能暂时这么改了
        Channel.Source source = cm.getCurrentSource();

        String ua = getUa(source);
        List<IMediaPlayer.Option> options = ijkCodec.getOptions();
        if (!TextUtils.isEmpty(ua)) {
            LogFactory.debug(SettingManager.class, "set ua {}", ua);
            List<IMediaPlayer.Option> o = CollectionsUtil.asList(new IMediaPlayer.Option(1, "user_agent", ua));
            o.addAll(options);
            options = o;
        }
        if (!TextUtils.isEmpty(url)) {
            videoView.setUrl(url);
        }
        videoView.setOptions(options);
        if (videoView.getCurrentPlayState() != LiveVideoView.STATE_IDLE
                && videoView.getCurrentPlayState() != LiveVideoView.STATE_START_ABORT) {
            videoView.replay(!cm.isLive());
        }
        videoView.start();
    }
    public void resetPlayer(int position) {
        resetPlayer(position, null);
    }

    private String getUa(Channel.Source source) {
        if (source == null) {
            return ObjectsUtil.Empty.STRING;
        }
        String ua = source.get("ua");
        LogFactory.debug(SettingManager.class, "Source ua {}", ua);
        if (TextUtils.isEmpty(ua)) {
            return ObjectsUtil.Empty.STRING;
        }
        String[] uas = new String[]{ua};
        if (ua.equalsIgnoreCase("pc")) {
            uas = mContext.getResources().getStringArray(R.array.pc);
        }
        else if (ua.equalsIgnoreCase("phone")) {
            uas = mContext.getResources().getStringArray(R.array.phone);
        }
        else if (ua.equalsIgnoreCase("table")) {
            uas = mContext.getResources().getStringArray(R.array.table);
        }
        else if (ua.equalsIgnoreCase("tv")) {
            uas = mContext.getResources().getStringArray(R.array.tv);
        }
        int idx = (int) ((Math.random() *100 * uas.length - 1) / 100);
        return uas[idx];
    }
}
